#include "maindialog.h"

#include "keybdef.h"
#include "keybconf.h"


bool MainDialog::readLocalSettings()
{
  // other options
  QSettings reg(QSettings::UserScope, "Sintegrial", "KeySwitch");

  // set sound value
  ui.cbSound->setChecked(reg.value("Sound", true).toBool());

  // set delay value
  ui.sbDelay->setValue(reg.value("Delay", 200).toInt());

  // set broadcast value
  ui.cbBroadcast->setChecked(reg.value("Broadcast", false).toBool());



  HKEY rootKey = 0;
  long res = RegOpenCurrentUser(KEY_READ, &rootKey);
  if (res != ERROR_SUCCESS)
      return false;

  HKEY key = 0;
  res = RegOpenKeyEx(rootKey, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Run"),
                     0, KEY_READ, &key);
  if (res != ERROR_SUCCESS)
  {
      RegCloseKey(rootKey);
      return false;
  }

  unsigned char value[1024];
  DWORD len = sizeof(value);

  // read autorun value
  res = RegQueryValueEx(key, _T("Key Switcher"), NULL, NULL, value, &len);

  ui.cbAutorun->setChecked(res == ERROR_SUCCESS);

  RegCloseKey(key);
  RegCloseKey(rootKey);
  return true;
}

bool MainDialog::writeLocalSettings()
{
  // other options
  QSettings reg(QSettings::UserScope, "Sintegrial", "KeySwitch");

  // set sound value
  reg.setValue("Sound", ui.cbSound->isChecked());

  // set delay value
  reg.setValue("Delay", ui.sbDelay->value());

  // set broadcast value
  reg.setValue("Broadcast", ui.cbBroadcast->isChecked());



  HKEY rootKey = 0;
  long res = RegOpenCurrentUser(KEY_WRITE, &rootKey);
  if (res != ERROR_SUCCESS)
      return false;

  HKEY key = 0;
  res = RegOpenKeyEx(rootKey, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Run"),
                     0, KEY_WRITE, &key);
  if (res != ERROR_SUCCESS)
  {
      RegCloseKey(rootKey);
      return false;
  }

  // set autorun value
  if (ui.cbAutorun->isChecked())
  {
    unsigned char value[1024] = {0};
    QString app = "\"" + qApp->applicationDirPath() + "/keyswitch.exe\"";
    app.replace("/","\\").toWCharArray((wchar_t*)value);

    DWORD len = app.size()*2;

    res = RegSetValueEx(key, _T("Key Switcher"), 0, REG_SZ, value, len);
  }
  else
  {
    // delete key
    RegDeleteValue(key, _T("Key Switcher"));
  }

  RegCloseKey(key);
  RegCloseKey(rootKey);
  return true;
}
